import java.io.*;

public class txtDivider {
    public static void main(String[] args) {
        if(args.length != 4){
            System.out.println("请输入正确的参数，例如：【待分割文件名（有后缀）、生成文件名（没有后缀）、分割行数、文件编码】");
            System.out.println("D:/txtDivide/server.log D:/txtDivide/serverLog 5000 UTF-8");
            return;
        }
        System.out.println("待分割文件名："+args[0]);
        System.out.println("生成文件名："+args[1]);
        System.out.println("分割行数："+args[2]);
        System.out.println("文件编码："+args[3]);

        String url = args[0];
        StringBuffer sb = new StringBuffer();
        String str = "";
        int line = 0;
        int txtNum = 0;
        File f = new File(url);

        BufferedReader br = null;
        try{
            int maxLine = Integer.parseInt(args[2]);
            br = new BufferedReader(new InputStreamReader(new FileInputStream(f),args[3]));
            boolean flag = true;
            while (flag){
                String out = args[1]+txtNum+".txt";
                while((str = br.readLine()) != null){
                    sb.append(str);
                    sb.append("\r\n");
                    line++;
                    if(line > maxLine){
                        break;
                    }
                }
                if(str == null){
                    System.out.println("读取完毕");
                    flag = false;
                }

                File outFile = new File(out);
                if(!outFile.exists()){
                    outFile.createNewFile();
                }
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),args[3]));
                bw.write(sb.toString());
                bw.flush();
                bw.close();

                //重置标志位等
                System.out.println("生成文件："+args[1]+""+txtNum+".txt");
                txtNum++;
                line = 0;
                sb.delete(0, sb.length());
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
            System.out.println("出现错误！见上方！");
            e.printStackTrace();
        }finally {
            try{
                br.close();
            }catch (Exception e){
                System.out.println(e.getMessage());
                System.out.println("关闭读文件流失败！");
                e.printStackTrace();
            }
        }
    }
}
